package com.yuke.cloud.common.security.auth.server;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * The class Pc access denied handler.
 *
 * @author
 */
@Slf4j
@Configuration
public class PcAccessDeniedHandler implements AccessDeniedHandler {
	@Resource
	private ObjectMapper objectMapper;

	@Value("${spring.profiles.active}")
	private String env;//当前激活的配置文件

	/**
	 * Handle.
	 *
	 * @param request  the request
	 * @param response the response
	 * @param e        the e
	 *
	 * @throws JsonProcessingException the json processing exception
	 */
	@Override
	public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException {
		log.info("PcAccessDeniedHandler->handle  com.yuke.cloud.common.security.auth.server");
		log.info("处理权限异常. e={}", e);
		Map<String, Object> result = new HashMap<>(3);
		result.put("code", 99990401);
		result.put("message", "无访问权限");
		String json = objectMapper.writeValueAsString(result);

		//add by wg 20181215 如果开发环境加上跨域配置（由于response直接输出，无法在配置类中进行配置，因此在response前直接配置跨域，生产环境在网关中已配置）
		if ("dev".equals(env)) { //开发环境对跨域进行配置
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setHeader("Access-Control-Allow-Credentials", "true");
			response.setHeader("Access-Control-Allow-Headers", "*");
			if("options".equalsIgnoreCase(request.getMethod()))
			{
				response.setStatus(HttpStatus.OK.value());
				return;
			}
		}
		response.setStatus(HttpStatus.UNAUTHORIZED.value());
		response.setContentType("application/json;charset=UTF-8");
		response.getWriter().write(json);
	}
}